package karileet.meeting.profile.adapter;

import java.util.List;

import karileet.meeting.profile.ProfileState;
import karileet.meeting.profile.R;
import karileet.meeting.profile.model.ComplexModel;
import karileet.meeting.profile.model.ui.ComplexModelHolder;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class ComplexModelAdapter extends ArrayAdapter<ComplexModel> {

	  private final List<ComplexModel> list;
	  private final Activity context;

	  public ComplexModelAdapter(Activity context, List<ComplexModel> list) {
	    super(context, R.layout.complex_row_item, list);
	    this.context = context;
	    this.list = list;
	  }
	  
	  
	  @Override
	  public View getView(int position, View convertView, ViewGroup parent) {
		  View view = null;
		  if (convertView == null) {
			  LayoutInflater inflator = context.getLayoutInflater();
		      view = inflator.inflate(R.layout.complex_row_item, null);
			  final ComplexModelHolder complexModelHolder = new ComplexModelHolder();
			  
			  complexModelHolder.setTitle((TextView) view.findViewById(R.id.rowTitle));
			  complexModelHolder.setTime((TextView) view.findViewById(R.id.rowTime));
			  complexModelHolder.setDescription((TextView) view.findViewById(R.id.rowDescription));
			  CheckBox cb = (CheckBox) view.findViewById(R.id.rowActive);
			  cb.setChecked(list.get(position).isSelected());
			  complexModelHolder.setCb(cb);
			  view.setTag(complexModelHolder);
			  complexModelHolder.setTag(list.get(position));
		  } else {
			  view = convertView;
			  //something i do not understand is omitted
			  
		  }
		  
		  ComplexModelHolder holder = (ComplexModelHolder) view.getTag();
		  holder.setTitleText(list.get(position).getTitle());
		  holder.setTimeText(list.get(position).getTime());
		  holder.setDescriptionText(list.get(position).getDescription());
		  holder.check(list.get(position).isSelected());
		  final int pos = position;
		  final ProfileState ps = new ProfileState(getContext());
		  holder.getCb().setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				list.get(pos).toggle();
				if (list.get(pos).getType() == 0) {
					ps.setScheduleStartEnabled(list.get(pos).isSelected());
				} else {
					ps.setScheduleStopEnabled(list.get(pos).isSelected());
				}
			}
		});
		  return view;
	  }
}
